/*
 * MIT License
 *
 * Copyright (c) 2025 Mark·虎
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 */

package com.hsxxherp.key.uia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hsxxherp.key.uia.entity.SysApplication;
import com.hsxxherp.key.uia.entity.SysApplicationGroup;
import com.hsxxherp.key.uia.mapper.SysApplicationGroupMapper;
import com.hsxxherp.key.uia.mapper.SysApplicationMapper;
import com.hsxxherp.key.uia.service.ISysApplicationGroupService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 应用分组服务实现
 *
 * @author Mark·虎（2486970363@qq.com）
 */
@Service
public class SysApplicationGroupServiceImpl extends ServiceImpl<SysApplicationGroupMapper, SysApplicationGroup> implements ISysApplicationGroupService {

    private static final Logger logger = LoggerFactory.getLogger(SysApplicationGroupServiceImpl.class);

    @Autowired
    private SysApplicationMapper sysApplicationMapper;

    @Override
    public SysApplicationGroup insertOrCreateApplicationGroup(SysApplicationGroup sysApplicationGroup) {
        // 检查是否有相同名称的 group_name
        QueryWrapper<SysApplicationGroup> nameQueryWrapper = new QueryWrapper<>();
        nameQueryWrapper.eq("group_name", sysApplicationGroup.getGroupName());
        if (count(nameQueryWrapper) > 0) {
            throw new RuntimeException("应用分组名称已存在，无法添加");
        }

        // 若检查通过，则调用父类的 save 方法进行保存
        boolean success = super.save(sysApplicationGroup);
        if (success) {
            // 插入成功后，由于 MyBatis-Plus 会自动回填主键，直接返回当前实体
            return sysApplicationGroup;
        }
        return null;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public SysApplicationGroup updateApplicationGroup(SysApplicationGroup sysApplicationGroup) {
        // 检查要修改的应用组是否存在
        SysApplicationGroup existingGroup = getById(sysApplicationGroup.getGroupId());
        if (existingGroup == null) {
            logger.error("要修改的应用组不存在，分组 ID: {}", sysApplicationGroup.getGroupId());
            throw new RuntimeException("要修改的应用组不存在");
        }

        // 检查修改后的应用组名称是否重复（排除当前要修改的应用组）
        QueryWrapper<SysApplicationGroup> nameQueryWrapper = new QueryWrapper<>();
        nameQueryWrapper.eq("group_name", sysApplicationGroup.getGroupName())
                .ne("group_id", sysApplicationGroup.getGroupId());
        if (count(nameQueryWrapper) > 0) {
            logger.error("应用分组名称已存在，无法修改，名称: {}", sysApplicationGroup.getGroupName());
            throw new RuntimeException("应用分组名称已存在，无法修改");
        }

        // 执行更新操作
        boolean success = updateById(sysApplicationGroup);
        if (success) {
            // 更新成功后，重新查询获取最新数据
            return getById(sysApplicationGroup.getGroupId());
        }
        logger.error("应用分组修改失败，分组 ID: {}", sysApplicationGroup.getGroupId());
        return null;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean deleteApplicationGroup(String groupId) {
        // 检查要删除的应用分组是否存在
        SysApplicationGroup existingGroup = getById(groupId);
        if (existingGroup == null) {
            logger.error("要删除的应用分组不存在，分组 ID: {}", groupId);
            throw new RuntimeException("要删除的应用分组不存在");
        }

        // 检查该分组下是否存在关联的应用
        QueryWrapper<SysApplication> appQueryWrapper = new QueryWrapper<>();
        appQueryWrapper.eq("group_id", groupId);
        if (sysApplicationMapper.selectCount(appQueryWrapper) > 0) {
            logger.error("该应用分组下存在关联的应用，无法删除，分组 ID: {}", groupId);
            throw new RuntimeException("该应用分组下存在关联的应用，无法删除");
        }

        // 执行软删除操作
        boolean success = removeById(groupId);
        if (success) {
            logger.info("应用分组删除成功，分组 ID: {}", groupId);
        } else {
            logger.error("应用分组删除失败，分组 ID: {}", groupId);
        }
        return success;
    }
}